package com.huanletao.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GsonTest {
    public static void main(String[] args) throws JsonProcessingException {
        Gson gson = new Gson();
        ObjectMapper objectMapper = new ObjectMapper();

        String json1 = "{\"userName\":\"小李飞刀\",\"age\":18,\"addTime\":1591851786568}";
        String json2 = "[{\"userName\":\"小李飞刀\",\"age\":18,\"addTime\":123}, {\"userName\":\"小李飞刀2\",\"age\":182,\"addTime\":1234}]";
        //2.把Json转换成map，必须使用 TypeReference , map的类型定义 可以根据实际情况来定，比如若值都是String那么就可以 Map<String, String>
        Map<String, Object> userBaseMap =  objectMapper.readValue(json1, new TypeReference<Map<String, Object>>() {});
        System.out.println("map: " + userBaseMap.get("userName"));


        //3.list<Bean>模式，必须用 TypeReference
        List<UserBase> userBaseList = objectMapper.readValue(json2, new TypeReference<List<UserBase>>() {});
        System.out.println("list: " + userBaseList.get(0).getUserName());


        //4.Bean[] 数组，必须用 TypeReference
        UserBase[] userBaseAry = objectMapper.readValue(json2, new TypeReference<UserBase[]>() {});
        System.out.println("ary: " + userBaseAry[0].getUserName());

       // objectMapper.readValue("", new TypeReference<List<GsonTest>>(){});
    }
}
